//
//  CouseSignUpViewController.m
//  TeacherNet
//
//  Created by slz on 2017/11/30.
//  Copyright © 2017年 bnsr. All rights reserved.
//

#import "CouseSignUpViewController.h"
#import "CourseSignUpCycleTableViewCell.h"
#import "CourseCommentUserTableViewCell.h"
#import "CourseTalkingTableViewCell.h"
#import "PlayVideoWebViewController.h"
#import "CourseCommentViewController.h"
#import "AddTalkingViewController.h"
#import "WJPopoverViewController.h"
#import "AddCourseNoteViewController.h"
#import "CouseSignUpNoteTableViewCell.h"
#import "SignUpSubView1.h"
#import "SignUpSubView2.h"
#import "NewWebViewController.h"
#import "UserNoteContenViewController.h"

#define kPageLeftRighrMargin 20

@implementation CourseSignUpHeaderNoteView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self){
        CALayer * lineLayer = [CALayer new];
        lineLayer.backgroundColor = kLineColor.CGColor;
        lineLayer.size = CGSizeMake(self.width, 1);
        lineLayer.left = 0;
        lineLayer.bottom = self.height;
        [self.layer addSublayer:lineLayer];
        
        _addButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addButton setTitle:@"+添加" forState:UIControlStateNormal];
        [_addButton setTitleColor:kDark_TextColor_Default forState:UIControlStateNormal];
        [_addButton addTarget:self action:@selector(addAction) forControlEvents:UIControlEventTouchUpInside];
        _addButton.titleLabel.fontSize = kFont_Size_Small_Title;
        [self addSubview:_addButton];
        [_addButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.mas_right);
            make.centerY.mas_equalTo(self.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(85, self.height));
        }];
        
        _listButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_listButton setTitle:@"全部笔记" forState:UIControlStateNormal];
        [_listButton setTitleColor:kDark_TextColor_Default forState:UIControlStateNormal];
        [_listButton addTarget:self action:@selector(allAction:andEvent:) forControlEvents:UIControlEventTouchUpInside];
        _listButton.titleLabel.fontSize = kFont_Size_Small_Title;
        [self addSubview:_listButton];
        [_listButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left);
            make.centerY.mas_equalTo(self.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(85, self.height));
        }];
    }
    return self;
}

- (void)allAction:(UIButton *)button andEvent:(UIEvent *)event{
    if ([_topView.delegate respondsToSelector:@selector(noteViewClickWithAllActionEvent:)]){
        [_topView.delegate noteViewClickWithAllActionEvent:event];
    }
}

- (void)addAction{
    if ([_topView.delegate respondsToSelector:@selector(noteViewClickWithAddAction)]){
        [_topView.delegate noteViewClickWithAddAction];
    }
}

@end

@implementation CustomRestMoreTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self){
        _titleLabel = [UILabel new];
        _titleLabel.textColor = kDark_TextColor_Default;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.fontSize = 14;
        [self.contentView addSubview:_titleLabel];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self.contentView);
        }];
        
    }
    return self;
}

@end

@implementation CourseSignUpTopHeaderView
- (instancetype)init
{
    self = [super init];
    if (self){
        self.frame = CGRectMake(0, 0, kScreenWidth, 150);
        self.backgroundColor = [UIColor colorWithRed:0  green:0 blue:0 alpha:.8];
        _courseIcon = [UIImageView new];
        _courseIcon.contentMode = UIViewContentModeScaleToFill;
        _courseIcon.layer.cornerRadius = 3;
        _courseIcon.layer.masksToBounds = YES;
        [self addSubview:_courseIcon];
        [_courseIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left).offset(25);
            make.centerY.mas_equalTo(self.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(85, 85));
        }];
        
        _courseNameLabel = [UILabel new];
        _courseNameLabel.fontSize = kFont_Size_Middle_Title;
        _courseNameLabel.textColor = kButtonColorBlue;
        [self addSubview:_courseNameLabel];
        [_courseNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(_courseIcon.mas_right).offset(13);
            make.top.mas_equalTo(_courseIcon.mas_top);
            make.right.mas_equalTo(self.mas_right).offset(-13);
        }];
        
        _courseLimitedLabel = [UILabel new];
        _courseLimitedLabel.fontSize = kFont_Size_Cotent_Nomal;
        _courseLimitedLabel.textColor = [UIColor whiteColor];
        [self addSubview:_courseLimitedLabel];
        [_courseLimitedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(_courseIcon.mas_right).offset(13);
            make.centerY.mas_equalTo(_courseIcon.mas_centerY);
        }];
        
    }
    return self;
}

- (void)layoutWithModel:(CourseSignUpModel *)model
{
    [_courseIcon sd_setImageWithURL:[NSURL URLWithString:kAPI_IMAGE_HOST(model.descModel.courseBanner)] randomPlaceHolder:YES];
    _courseNameLabel.text = model.descModel.courseName;
    _courseLimitedLabel.text = [NSString stringWithFormat:@"有效期：%@ - %@",model.descModel.courseStartTime,model.descModel.courseEndTime];
    
    [self setWithRankUser:model.listModel];
}

- (void)setWithRankUser:(NSArray *)userList
{
    if (!userList || userList.count == 0) return;
    UILabel * aaaa = [UILabel new];
    aaaa.text = @"学霸榜：";
    aaaa.textColor = [UIColor whiteColor];
    aaaa.fontSize = kFont_Size_Cotent_Nomal;
    [self addSubview:aaaa];
    [aaaa mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_courseIcon.mas_right).offset(13);
        make.bottom.mas_equalTo(_courseIcon.mas_bottom);
    }];
   // 113 + 45
    NSInteger imageWidth = 22;
    NSInteger imageSpace = 6;
    for (int i = 0; i < userList.count; i++) {
        if (i >= 5) break;
        TTUserModel * model = userList[i];
        UIImageView * imageView = [UIImageView new];
        [imageView sd_setImageWithURL:[NSURL URLWithString:kAPI_IMAGE_HOST(model.avarater)] randomPlaceHolder:YES];
        [self addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(aaaa.mas_right).offset(i * (imageWidth + imageSpace));
            make.size.mas_equalTo(CGSizeMake(imageWidth, imageWidth));
            make.centerY.mas_equalTo(aaaa.mas_centerY);
        }];
    }
}
@end


@implementation CourseSignUpTopContinueView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self){
        self.backgroundColor = kLineColor_Gray_Default;
        _currentCourseLabel = [UILabel new];
        _currentCourseLabel.textColor = kDark_TextColor_Default;
        _currentCourseLabel.fontSize = kFont_Size_Cotent_Nomal;
        [self addSubview:_currentCourseLabel];
        [_currentCourseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left).offset(kPageLeftRighrMargin);
            make.centerY.mas_equalTo(self.mas_centerY);
        }];
        
        _continueButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _continueButton.backgroundColor = kButtonColorBlue;
        _continueButton.layer.cornerRadius = 8;
        _continueButton.layer.masksToBounds = YES;
        [_continueButton addTarget:self action:@selector(continueStudy) forControlEvents:UIControlEventTouchUpInside];
        [_continueButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _continueButton.titleLabel.fontSize = kFont_Size_Cotent_Nomal;
        [self addSubview:_continueButton];
        [_continueButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.mas_right).offset(-kPageLeftRighrMargin);
            make.centerY.mas_equalTo(self.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(82, 23));
        }];
        
        CALayer * lineLayer = [CALayer new];
        lineLayer.backgroundColor = kLineColor.CGColor;
        lineLayer.size = CGSizeMake(self.width, 1);
        lineLayer.left = 0;
        lineLayer.bottom = self.height;
        [self.layer addSublayer:lineLayer];
    }
    return self;
}

- (void)continueStudy{
    if ([_topView.delegate respondsToSelector:@selector(buttonClickWithContinue)]){
        [_topView.delegate buttonClickWithContinue];
    }
}

- (void)setWithTitle:(NSString *)title andState:(CGFloat)progress
{
    if (progress <= 0){
        [_continueButton setTitle:@"开始学习" forState:UIControlStateNormal];
        _currentCourseLabel.text = @"未开始学习";
    }else if (progress > 0 && progress < 1){
        [_continueButton setTitle:@"继续学习" forState:UIControlStateNormal];
        _currentCourseLabel.text = [NSString stringWithFormat:@"已学到：%@",title];
    }else
    {
        _currentCourseLabel.text = @"";
        _continueButton.userInteractionEnabled = NO;
        _continueButton.backgroundColor = [UIColor grayColor];
        [_continueButton setTitle:@"已学完" forState:UIControlStateNormal];
    }
}

@end


@implementation CourseSignUpProgressView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self){
        _progressLabel = [UILabel new];
        _progressLabel.fontSize = 15;
        [self addSubview:_progressLabel];
        [_progressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left).offset(23);
            make.top.mas_equalTo(12);
        }];
        
        CGFloat layerWith = kScreenWidth - 40;
        CALayer * fullLayer = [CALayer new];
        fullLayer.backgroundColor = [UIColor colorWithRGB:0xE9EAEB].CGColor;
        fullLayer.cornerRadius = 5;
        fullLayer.masksToBounds = YES;
        fullLayer.size = CGSizeMake(layerWith, 13);
        fullLayer.origin = CGPointMake(20, 50);
        [self.layer addSublayer:fullLayer];
        
        _progressLayer = [CALayer new];
        _progressLayer.backgroundColor = kButtonColorBlue.CGColor;
        _progressLayer.cornerRadius = 5;
        _progressLayer.masksToBounds = YES;
        _progressLayer.height = fullLayer.height;
        _progressLayer.origin = CGPointMake(0, 0);
        [fullLayer addSublayer:_progressLayer];
        
        CALayer * lineLayer = [CALayer new];
        lineLayer.backgroundColor = kLineColor.CGColor;
        lineLayer.size = CGSizeMake(self.width, 1);
        lineLayer.left = 0;
        lineLayer.bottom = self.height;
        [self.layer addSublayer:lineLayer];
    }
    return self;
}

- (void)setProgress:(CGFloat)progress
{
    CGFloat layerWith = kScreenWidth - 40;
    CGFloat progressWith = layerWith * progress;
    _progressLayer.width = progressWith;
    
    NSInteger progressInt = progress * 100;
    if (progressInt < 0 || progressInt > 100)
    {
        progressInt = 0;
    }
    NSAttributedString * attString = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%ld",progressInt] attributes:@{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:20]}];
    NSMutableAttributedString * firseAtt = [[NSMutableAttributedString alloc]initWithString:@"学习进度"];
    [firseAtt appendAttributedString:attString];
    [firseAtt appendAttributedString:[[NSAttributedString alloc]initWithString:@"%"]];
    _progressLabel.attributedText = firseAtt;
}
@end


@implementation CourseSignUpButtonView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self){
        self.backgroundColor = kLineColor_Gray_Default;
        
        NSArray * buttonTitles = @[@"课时",@"笔记",@"问答",@"评价"];
        CGFloat buttonWidth = kScreenWidth * .25;
        
        for (int i = 0; i < buttonTitles.count; i++)
        {
            UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
            NSString * title = buttonTitles[i];
            button.origin = CGPointMake(i * buttonWidth, 0);
            button.size = CGSizeMake(buttonWidth, self.height);
            button.titleLabel.fontSize = kFont_Size_Small_Title;
            [button setTitle:title forState:UIControlStateNormal];
            [button setTitleColor:i == 0 ? kButtonColorBlue : kDark_TextColor_Default forState:UIControlStateNormal];
            button.tag = i;
            [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:button];
        }
        
        _slider = [CALayer new];
        _slider.backgroundColor = kButtonColorBlue.CGColor;
        _slider.size = CGSizeMake(buttonWidth, 4);
        _slider.left = 0;
        _slider.bottom = self.height;
        
        CALayer * lineLayer = [CALayer new];
        lineLayer.backgroundColor = kLineColor.CGColor;
        lineLayer.size = CGSizeMake(self.width, 1);
        lineLayer.left = 0;
        lineLayer.bottom = self.height;
        [self.layer addSublayer:lineLayer];
        
        [self.layer addSublayer:_slider];
    }
    return self;
}

- (void)buttonClick:(UIButton *)button
{
    for (id obj in self.subviews) {
        if ([obj isKindOfClass:[UIButton class]]){
            UIButton * objButton = obj;
            [objButton setTitleColor:kDark_TextColor_Default forState:UIControlStateNormal];
        }
    }
    [button setTitleColor:kButtonColorBlue forState:UIControlStateNormal];
    CGFloat buttonWidth = kScreenWidth * .25;
    NSInteger tag = button.tag;
    _slider.left = buttonWidth * tag;
    if ([_topView.delegate respondsToSelector:@selector(buttonClickWithSliderIndex:)]){
        [_topView.delegate buttonClickWithSliderIndex:tag];
    }
}
@end

@implementation CourseTalkingToolView
-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self){
        CALayer * lineLayer = [CALayer new];
        lineLayer.backgroundColor = kLineColor.CGColor;
        lineLayer.size = CGSizeMake(self.width, 1);
        lineLayer.left = 0;
        lineLayer.bottom = self.height;
        [self.layer addSublayer:lineLayer];
        
        _addButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addButton setTitle:@"+添加" forState:UIControlStateNormal];
        [_addButton setTitleColor:kDark_TextColor_Default forState:UIControlStateNormal];
        [_addButton addTarget:self action:@selector(addAction) forControlEvents:UIControlEventTouchUpInside];
        _addButton.titleLabel.fontSize = kFont_Size_Small_Title;
        [self addSubview:_addButton];
        [_addButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.mas_right);
            make.centerY.mas_equalTo(self.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(85, self.height));
        }];
        
        _listButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_listButton setTitle:@"全部" forState:UIControlStateNormal];
        [_listButton setTitleColor:kDark_TextColor_Default forState:UIControlStateNormal];
        [_listButton addTarget:self action:@selector(allAction:andEvent:) forControlEvents:UIControlEventTouchUpInside];
        _listButton.titleLabel.fontSize = kFont_Size_Small_Title;
        [self addSubview:_listButton];
        [_listButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.mas_left);
            make.centerY.mas_equalTo(self.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(85, self.height));
        }];
    }
    return self;
}

- (void)allAction:(UIButton *)button andEvent:(UIEvent *)event{
    if ([_topView.delegate respondsToSelector:@selector(talkingViewClickWithAllActionEvent:)]){
        [_topView.delegate talkingViewClickWithAllActionEvent:event];
    }
}

- (void)addAction{
    if ([_topView.delegate respondsToSelector:@selector(talkingViewClickWithAddAction)]){
        [_topView.delegate talkingViewClickWithAddAction];
    }
}

@end

@implementation CouseSignUpViewTopView
- (instancetype)init
{
    self = [super init];
    if (self){
        self.backgroundColor = [UIColor whiteColor];
        self.frame = CGRectMake(0, 0, kScreenWidth, 310);
        _headerView = [CourseSignUpTopHeaderView new];
        _continueView = [[CourseSignUpTopContinueView alloc]initWithFrame:CGRectMake(0, _headerView.bottom, _headerView.width, 40)];
        _continueView.topView = self;
        _progressView = [[CourseSignUpProgressView alloc]initWithFrame:CGRectMake(0, _continueView.bottom, _headerView.width, 80)];
        _buttonView = [[CourseSignUpButtonView alloc]initWithFrame:CGRectMake(0, _progressView.bottom, _headerView.width, 40)];
        _buttonView.topView = self;
        _talkingView = [[CourseTalkingToolView alloc]initWithFrame:CGRectMake(0, _buttonView.bottom, _headerView.width, 40)];
        _talkingView.topView = self;
        _talkingView.hidden = YES;
        
        _commentHeader = [[CourseCommentTableHeaderView alloc]initWithFrame:CGRectMake(0, _buttonView.bottom, _headerView.width, 0)];
        _commentHeader.hidden = YES;
        _noteView = [[CourseSignUpHeaderNoteView alloc]initWithFrame:CGRectMake(0, _buttonView.bottom, _headerView.width, 41)];
        _noteView.topView = self;
        _noteView.hidden = YES;

        
        [self addSubview:_headerView];
        [self addSubview:_continueView];
        [self addSubview:_progressView];
        [self addSubview:_buttonView];
        [self addSubview:_talkingView];
        [self addSubview:_commentHeader];
        [self addSubview:_noteView];
    }
    return self;
}

- (void)layoutWithPageModel:(CourseSignUpModel *)model
{
    [_headerView layoutWithModel:model];
    
    CGFloat progress = model.allCourseCount > 0 ? (float)model.currentCourseCount/(float)model.allCourseCount : 0;
    [_progressView setProgress:progress];
    [_continueView setWithTitle:model.currentCourseName andState:progress];
}

- (CGFloat)heightForSubView
{
    return _headerView.height + _continueView.height + _progressView.height + _buttonView.height + _commentHeader.height;
}

-(void)setHeight:(CGFloat)height
{
    CGRect frame = self.frame;
    self.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);
    if (height == 310)
    {
        _talkingView.hidden = YES;
        _commentHeader.hidden = YES;
        _noteView.hidden = YES;
    }else if (height == 350)
    {
        _noteView.hidden =YES;
        _talkingView.hidden = NO;
        _commentHeader.hidden = YES;
    }else if (height == 351)
    {
        _noteView.hidden =NO;
        _talkingView.hidden = YES;
        _commentHeader.hidden = YES;
    }else{
        _talkingView.hidden = YES;
        _commentHeader.hidden = NO;
        _noteView.hidden = YES;
    }
}

@end

@interface CouseSignUpViewController ()<UITableViewDelegate,UITableViewDataSource,CouseSignUpViewTopViewDelegate,CouseSignUpNoteTableViewCellDelegate,AddCourseNoteViewControllerDelegate>
@property (nonatomic,strong) YWTableView *tableView;
@property (nonatomic,strong) SignUpSubView1*subView1;
@property (nonatomic,strong) SignUpSubView2*subView2;
@property (nonatomic,strong) CouseSignUpViewTopView *topView;
@property (nonatomic,strong) CourseSignUpModel *pageModel;
@property (nonatomic,strong) CourseCommentPageModel *commentModel;
@property (nonatomic,strong) TTTalkingListModel *talkingListModel;
@property (nonatomic,strong) TTCourseNoteListModel *noteListModel;
@property (nonatomic,strong)WJPopoverViewController *rightPopView;
@property (nonatomic,strong) UITableView *popTableView;
@property (nonatomic,strong) UITableView *notePopTableView;

@property (nonatomic,strong) UIButton *signUpButton;
@property(nonatomic,assign) NSInteger currentIndex;

@property (nonatomic,strong) id commentObj;
@property (nonatomic,strong) id talkingObj;
@property (nonatomic,strong) id noteObj;
@end

@implementation CouseSignUpViewController
{
    NSArray *_popTitles;
    NSArray *_notePopTitles;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.showNavigationBar = YES;
    self.currentIndex = 0;
    [self setControllerTitle:@"我的学习"];
    [self initSubViews];
    [self.tableView.mj_header beginRefreshing];
    _popTitles = @[@"全部",@"我的提问",@"我的回答"];
    _notePopTitles = @[@"全部",@"我的笔记"];
    // Do any additional setup after loading the view.
}

- (UITableView *)popTableView {
    if(_popTableView == nil) {
        _popTableView = [[UITableView alloc] init];
        _popTableView.frame = CGRectMake(0, 0, 91, 120);
        _popTableView.backgroundColor = [UIColor whiteColor];
        _popTableView.delegate = self;
        _popTableView.dataSource = self;
        _popTableView.bounces = NO;
        _popTableView.rowHeight = 40;
    }
    return _popTableView;
}
- (UITableView *)notePopTableView {
    if(_notePopTableView == nil) {
        _notePopTableView = [[UITableView alloc] init];
        _notePopTableView.frame = CGRectMake(0, 0, 91, 80);
        _notePopTableView.backgroundColor = [UIColor whiteColor];
        _notePopTableView.delegate = self;
        _notePopTableView.dataSource = self;
        _notePopTableView.bounces = NO;
        _notePopTableView.rowHeight = 40;
    }
    return _notePopTableView;
}

- (void)requestData
{
    [BaseHttpTool get:kAPI_COURSE_DETAIL_SIGNUP_GETINFO params:@{@"id":self.couseId,@"class_id":_classId,@"user_id":[MFWSdkEnvironment sharedInstance].userInfo.uid} success:^(id responseObj) {
        [_tableView.mj_header endRefreshing];
        
        _pageModel = [CourseSignUpModel yy_modelWithDictionary:[[MFWJson jsonWithObject:responseObj] toDic]];
        if (_pageModel)
        {
            [_topView layoutWithPageModel:_pageModel];
            [_tableView reloadData];
        }
    } failure:^(NSError *error) {
        [self.view showTip:error.localizedDescription];
    }];
}

- (void)initSubViews
{
    UIBarButtonItem * backItem = [UIBarButtonItem itemWithImage:@"back_icon" selectImage:@"" addTarget:self andAction:@selector(backAction)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    _tableView = [[YWTableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (_currentIndex == 0){
            [self requestData];
        }else if (_currentIndex == 1){
            [self requestNoteWithType:@"0"];
        }else if (_currentIndex == 2){
            [self requestTalkingListWithType:@""];
        }else{
            [self requestCommentList];
        }
    }];
    
    
    _topView = [CouseSignUpViewTopView new];
    _topView.delegate = self;
    [_tableView setTableHeaderView:_topView];
    
    _signUpButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _signUpButton.backgroundColor = kButtonColorBlue;
    [_signUpButton setTitle:@"我要评论" forState:UIControlStateNormal];
    [_signUpButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_signUpButton addTarget:self action:@selector(commentAction) forControlEvents:UIControlEventTouchUpInside];
    _signUpButton.titleLabel.fontSize = kFont_Size_Small_Title;
    [self.view addSubview:_signUpButton];
    [_signUpButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(55);
        make.height.mas_equalTo(55);
    }];
    
    CALayer * lineLayer = [CALayer new];
    lineLayer.size = CGSizeMake(kScreenWidth, 1);
    lineLayer.backgroundColor = kLineColor.CGColor;
    lineLayer.origin = CGPointMake(0, 0);
    [_signUpButton.layer addSublayer:lineLayer];
}

- (void)commentAction{
    if (!_commentObj)
    {
        [self.view showTip:@"网络错误~"];
        return;
    }
    NSDictionary * dict = [[MFWJson jsonWithObject:_commentObj] toDic];
    CourseCommentPageModel * pageModel = [CourseCommentPageModel yy_modelWithDictionary:dict];
    CourseCommentViewController * commentController = [CourseCommentViewController new];
    commentController.courseId = self.couseId;
    commentController.commentList = pageModel.quickComment;
    [self.navigationController pushViewController:commentController animated:YES];
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - UITableViewDelegate && UITableViewDataSource

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if ([tableView isEqual:_popTableView] || [tableView isEqual:_notePopTableView]){
        return NULL;
    }
    if (_currentIndex == 0)
    {
        UIView * backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        
        UIImageView * imageView = [UIImageView new];
        imageView.image = [UIImage imageNamed:@"course_type_arrow"];
        imageView.size = CGSizeMake(22, 22);
        imageView.centerY = 22;
        imageView.left = 18;
        [backView addSubview:imageView];
        
        UILabel * titleLabel = [UILabel new];
        titleLabel.size = CGSizeMake(kScreenWidth - 60, 37);
        titleLabel.left = imageView.right + 5;
        titleLabel.centerY = imageView.centerY;
        titleLabel.textColor = kDark_TextColor_Default;
        titleLabel.fontSize = 15;
        [backView addSubview:titleLabel];
        
        CourseSignUpCycleModel * subModel = _pageModel.cycleModel[section];
        
        titleLabel.text = subModel.title;
        return backView;
    }else
    {
        return NULL;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([tableView isEqual:_popTableView] || [tableView isEqual:_notePopTableView]){
        return CGFLOAT_MIN;
    }
    if (_currentIndex == 0)
    {
        return 44;
    }else
    {
        return CGFLOAT_MIN;
    }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_popTableView]){
        static NSString * reuserIdentifier = @"CustomRestMoreTableViewCell";
        CustomRestMoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuserIdentifier];
        if (!cell) {
            cell = [[CustomRestMoreTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.titleLabel.text = _popTitles[indexPath.row];
        return cell;
    }
    if ([tableView isEqual:_notePopTableView]){
        static NSString * reuserIdentifier = @"CustomRestMoreTableViewCell";
        
        CustomRestMoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuserIdentifier];
        if (!cell) {
            cell = [[CustomRestMoreTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.titleLabel.text = _notePopTitles[indexPath.row];
        return cell;
    }
    
    if (_currentIndex == 0)
    {
        static NSString * reuserIdentifier = @"CourseSignUpCycleTableViewCell";
        CourseSignUpCycleTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuserIdentifier];
        if (!cell){
            cell = [[CourseSignUpCycleTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        CourseSignUpCycleModel * subModel = _pageModel.cycleModel[indexPath.section];
        CourseSignUpCycleModel * model = subModel.subList[indexPath.row];
        [cell layoutWithModel:model andCurrentCourseId:_pageModel.currentCourseId];
        return cell;
    }else if (_currentIndex == 1)
    {
        static NSString * reuserIdentifier = @"CouseSignUpNoteTableViewCell";
        CouseSignUpNoteTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuserIdentifier];
        if (!cell){
            cell = [[CouseSignUpNoteTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserIdentifier];
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        TTCourseNoteModel * model = _noteListModel.noteList[indexPath.row];
        [cell layoutWithModel:model];
        return cell;
    }else if (_currentIndex == 2)
    {
        TTTalkingModel * model = _talkingListModel.talkingList[indexPath.row];
        static NSString * reuserIdentifier = @"CourseTalkingTableViewCell";
        CourseTalkingTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuserIdentifier];
        if (!cell){
            cell = [[CourseTalkingTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell layoutWithTalkingModel:model];
        return cell;
    }else{
        CourseUserCommentModel * model = _commentModel.userComments[indexPath.row];
        static NSString * reuserIdentifier = @"CourseCommentUserTableViewCell";
        CourseCommentUserTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuserIdentifier];
        if (!cell) {
            cell = [CourseCommentUserTableViewCell instanceWithNibName:@"CourseCommentUserTableViewCell" owner:nil];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.timeLabel.text = model.commentDate;
        cell.UserNameLabel.text = model.userName;
        cell.commentContentLabel.text = model.commentContent;
        cell.ratingView.rating = model.rating;
        [cell.avatar sd_setImageWithURL:[NSURL URLWithString:kAPI_IMAGE_HOST(model.avater)] randomPlaceHolder:YES];
        return cell;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:_popTableView]){
        return 3;
    }
    if ([tableView isEqual:_notePopTableView]){
        return 2;
    }
    if (_currentIndex == 0)
    {
        CourseSignUpCycleModel * subModel = _pageModel.cycleModel[section];
        return subModel.subList.count;
    }else if (_currentIndex == 1)
    {
        return  _noteListModel.noteList.count;
    }else if (_currentIndex == 2)
    {
        return _talkingListModel.talkingList.count;
    }else{
        return _commentModel.userComments.count;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([tableView isEqual:_popTableView]){
        return 1;
    }
    if (_currentIndex == 0)
    {
        return _pageModel.cycleModel.count;
    }else if (_currentIndex == 1)
    {
        return  1;
    }else if (_currentIndex == 2)
    {
        return 1;
    }else{
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_popTableView] || [tableView isEqual:_notePopTableView]){
        return 40;
    }
    if (_currentIndex == 0)
    {
        return 75;
    }else if (_currentIndex == 1)
    {
        return  100;
    }else if (_currentIndex == 2)
    {
        return 80;
    }else{
        return 100;
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_popTableView]){
        NSString * type;
        switch (indexPath.row) {
            case 0:
                type = @"";
                break;
            case 1:
                type = @"1";
                break;
            case 2:
                type = @"2";
                break;
            default:
                break;
        }
        [self requestTalkingListWithType:type];
        [_rightPopView dissPopoverViewWithAnimation:YES];
        [_topView.talkingView.listButton setTitle:_popTitles[indexPath.row] forState:UIControlStateNormal];
        return;
    }
    if ([tableView isEqual:_notePopTableView]){
        [self requestNoteWithType:[NSString stringWithFormat:@"%ld",indexPath.row]];
        [_rightPopView dissPopoverViewWithAnimation:YES];
        [_topView.noteView.listButton setTitle:_notePopTitles[indexPath.row] forState:UIControlStateNormal];
        return;
    }
    
    if (_currentIndex == 1){
        TTCourseNoteModel * model = _noteListModel.noteList[indexPath.row];
        UserNoteContenViewController * noteController = [[UserNoteContenViewController alloc]init];
        noteController.noteModel = model;
        [self.navigationController pushViewController:noteController animated:YES];
        return;
    }
    

    if (_currentIndex == 2){
        NSString * urlHost = kAPI_HOST(@"/edu_yun/course/read_question_m.action");
        TTTalkingModel * model = _talkingListModel.talkingList[indexPath.row];
        NSString * url = [NSString stringWithFormat:@"%@?question_id=%@&user_id=%@",urlHost,model.talkId,[MFWSdkEnvironment sharedInstance].userInfo.uid];
        NewWebViewController * wenController = [[NewWebViewController alloc]init];
        wenController.url = url;
        [self.navigationController pushViewController:wenController animated:YES];
        return;
    }
    if (_currentIndex == 0){
        NSString * urlHost = kAPI_HOST(@"/edu_yun/course/to_study_m.action");
        CourseSignUpCycleModel * subModel = _pageModel.cycleModel[indexPath.section];
        CourseSignUpCycleModel * model = subModel.subList[indexPath.row];
        NSString * url =  [NSString stringWithFormat:@"%@?id=%@&class_id=%@&user_id=%@",urlHost,model.courseId,self.classId,[MFWSdkEnvironment sharedInstance].userInfo.uid];
        PlayVideoWebViewController * webViewController = [[PlayVideoWebViewController alloc]init];
        webViewController.url = url;
        [self.navigationController pushViewController:webViewController animated:YES];
        return;
    }
}

#pragma mark topViewDeleaget

-(void)buttonClickWithContinue
{
    NSString * urlHost = kAPI_HOST(@"/edu_yun/course/to_study_m.action");
    NSString * url = [NSString stringWithFormat:@"%@?id=%@&class_id=%@&user_id=%@",urlHost,self.couseId,self.classId,[MFWSdkEnvironment sharedInstance].userInfo.uid];
    if (_pageModel.currentCourseId && _pageModel.currentCourseId.length > 0){
        PlayVideoWebViewController * webViewController = [[PlayVideoWebViewController alloc]init];
        webViewController.url = url;
        [self.navigationController pushViewController:webViewController animated:YES];
    }
}


-(void)noteViewClickWithAddAction
{
    AddCourseNoteViewController * add = [AddCourseNoteViewController new];
    add.delegate = self;
    add.classId = self.classId;
    add.couseId = self.couseId;
    [self.navigationController pushViewController:add animated:YES];
}

- (void)noteViewClickWithAllActionEvent:(UIEvent *)event{
    self.rightPopView = [[WJPopoverViewController alloc] initWithShowView:self.notePopTableView];
    [self.rightPopView showPopoverWithTouch:event animation:YES];
}

-(void)talkingViewClickWithAddAction
{
    @weakify(self);
    AddTalkingViewController * add = [AddTalkingViewController new];
    add.classId = self.classId;
    add.courseId = self.couseId;
    add.completion = ^(BOOL result)
    {
        if (result)
        {
            @strongify(self);
            [self requestTalkingListWithType:@""];
        }
    };
    [self.navigationController pushViewController:add animated:YES];
}

-(void)talkingViewClickWithAllActionEvent:(UIEvent *)event
{
    self.rightPopView = [[WJPopoverViewController alloc] initWithShowView:self.popTableView];
    [self.rightPopView showPopoverWithTouch:event animation:YES];
}

- (void)requestTalkingListWithType:(NSString *)type
{
    if (type.length == 0){
        [_topView.talkingView.listButton setTitle:@"全部" forState:UIControlStateNormal];
    }
    [self requestTalkingObjType:type Comletion:^(id obj, BOOL requestResult) {
        if (!requestResult)
        {
            [self.view showTip:@"网络错误~"];
            return;
        }
        NSDictionary * dict = [[MFWJson jsonWithObject:obj] toDic];
        if (!dict || dict.count == 0) return;
        TTTalkingListModel * model = [TTTalkingListModel yy_modelWithDictionary:dict];
        _talkingListModel = model;
        [self.tableView reloadData];
    }];
}

- (void)requestNoteWithType:(NSString *)type
{
    if ([type isEqualToString:@"0"]){
        [_topView.noteView.listButton setTitle:@"全部" forState:UIControlStateNormal];
    }
    [self requestWithNoteListType:type completion:^(id obj, BOOL requestResult) {
        if (!requestResult)
        {
            [self.view showTip:@"网络错误~"];
            return;
        }
        NSDictionary * dict = [[MFWJson jsonWithObject:obj] toDic];
        if (!dict || dict.count == 0) return;
        TTCourseNoteListModel * model = [TTCourseNoteListModel yy_modelWithDictionary:dict];
        _noteListModel = model;
        [self.tableView reloadData];
    }];
}

- (void)requestCommentList
{
    [self requestCommentOjbComletion:^(id obj, BOOL requestResult) {
        if (!requestResult)
        {
            [self.view showTip:@"网络错误~"];
            return;
        }
        NSDictionary * dict = [[MFWJson jsonWithObject:obj] toDic];
        if (!dict || dict.count == 0) return;
        CourseCommentPageModel * pageModel = [CourseCommentPageModel yy_modelWithDictionary:dict];
        _commentModel = pageModel;
        [_topView.commentHeader.averageCommentView setWithStarFloat:_commentModel.commentAverage peopleCount:_commentModel.commentCount];
        _topView.commentHeader.commentView.height =  [_topView.commentHeader.commentView updateWithQuickComments:_commentModel.quickComment];
        _topView.commentHeader.height = _topView.commentHeader.commentView.height + _topView.commentHeader.averageCommentView.height;
        _topView.height = [_topView heightForSubView];
        [self.tableView setTableHeaderView:NULL];
        [self.tableView setTableHeaderView:_topView];
        [self.tableView reloadData];
    }];
}

-(void)buttonClickWithSliderIndex:(NSInteger)index
{
    _currentIndex = index;
    if (index == 0)
    {
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        [_signUpButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self.view.mas_bottom).offset(55);
        }];
        _topView.height = 310;
    }else if (index == 1)
    {
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        [_signUpButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self.view.mas_bottom).offset(55);
        }];
        
        if (!_noteObj){
            [self requestNoteWithType:@"0"];
        }
        _topView.height = 351;

    }else if (index == 2)
    {
        [_signUpButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self.view.mas_bottom).offset(55);
        }];
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);

        if (!_talkingObj)
        {
            [self requestTalkingListWithType:@""];
        }
        _topView.height = 350;
    }else
    {
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 55, 0);

        [_signUpButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }];
        if (!_commentObj)
        {
            [self requestCommentList];
        }else
        {
            _topView.height = [_topView heightForSubView];
        }
    }
    [self.tableView setTableHeaderView:NULL];
    [self.tableView setTableHeaderView:_topView];
    [self.tableView reloadData];
}



- (void)pageUpdateWithIndex:(NSInteger)index
{
    
}

- (void)requestWithNoteListType:(NSString *)type completion:(void(^)(id obj, BOOL requestResult))completion
{
    [BaseHttpTool get:kAPI_COURSE_NOTE  params:@{@"course_id":self.couseId,@"status":type,@"user_id":[MFWSdkEnvironment sharedInstance].userInfo.uid} success:^(id responseObj) {
        [_tableView.mj_header endRefreshing];
        _noteObj = responseObj;
        completion(responseObj,YES);
    } failure:^(NSError *error) {
        [_tableView.mj_header endRefreshing];
        completion(NULL,NO);
    }];
}

- (void)requestTalkingObjType:(NSString *)type Comletion:(void(^)(id obj, BOOL requestResult))comletion
{
    NSDictionary * params;
    if (type && type.length > 0){
        params = @{@"source_id":self.couseId,@"source_type":@"0",@"type":type,@"user_id":[MFWSdkEnvironment sharedInstance].userInfo.uid};
    }else{
        params = @{@"source_id":self.couseId,@"source_type":@"0",@"user_id":[MFWSdkEnvironment sharedInstance].userInfo.uid};
    }
    [BaseHttpTool get:kAPI_COURSE_STUDY_TALKING_LIST  params:params success:^(id responseObj) {
        [_tableView.mj_header endRefreshing];
        _talkingObj = responseObj;
        comletion(_talkingObj,YES);
    } failure:^(NSError *error) {
        [_tableView.mj_header endRefreshing];
        comletion(NULL,NO);
    }];
}

- (void)requestCommentOjbComletion:(void(^)(id obj,BOOL requestResult))comletion
{
    [BaseHttpTool get:kAPI_COURSE_DETAIL_COMMENT  params:@{@"id":self.couseId} success:^(id responseObj) {
        [_tableView.mj_header endRefreshing];
        _commentObj = responseObj;
        comletion(_commentObj,YES);
    } failure:^(NSError *error) {
        comletion(NULL,NO);
        [_tableView.mj_header endRefreshing];
    }];
}

#pragma  mark - CouseSignUpNoteTableViewCellDelegate

-(void)cellDidClickLikeButtonWithNoteId:(NSString *)noteId
{
    [BaseHttpTool get:kAPI_COURSE_NOTE_LIKE_ACTION params:@{@"user_id":[MFWSdkEnvironment sharedInstance].userInfo.uid,@"note_id":noteId} success:^(id responseObj) {
        
    } failure:^(NSError *error) {
        [self.view showTip:error.localizedDescription];
    }];
}

#pragma mark - AddCourseNoteViewControllerDelegate

-(void)addNoteWithResult:(BOOL)result andIsShare:(BOOL)isShare
{
    if (result && isShare){
        [self requestNoteWithType:@"0"];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
